<template>
  <div class="app-container">
    <div class="section-add">
      <el-button v-waves type="primary" size="mini" icon="el-icon-plus" @click="handleCreate">Add</el-button>
      <div class="link-type" @click="dialogViewsVisible = true">
        <svg-icon icon-class="eye-open" />
      </div>
    </div>
    <!-- 数据表格 -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      fit
      style="width: 100%;"
      row-key="id"
      :expand-row-keys="expandRowKeys"
      @expand-change="onExpandChange"
    >
      <el-table-column align="center" type="expand">
        <template slot-scope="{row}">
          <section-item
            :data="row.items"
            :type-list="calendarTypeOptions"
            :row-key="`${row.id}`"
            @update="onUpdateList"
          />
        </template>
      </el-table-column>
      <el-table-column label="Index" type="index" width="100" align="center"></el-table-column>
      <el-table-column label="Type" prop="types">
        <template slot-scope="{row}">
          <el-tag v-for="(tag, idx) in row.types" :key="idx" style="margin-left: 10px;">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button
            v-waves
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(row, $index)"
          >Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <el-dialog :visible.sync="dialogFormVisible">
      <div slot="title">
        <span>Create Section</span>
        <strong style="margin-left:24px;font-size: 12px;color: red;">注意：section 中至少包含一个内容</strong>
      </div>
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="Type" prop="type">
          <el-select
            v-model="temp.type"
            class="filter-item"
            placeholder="Please select"
            @change="onChangeType"
          >
            <el-option v-for="item in calendarTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <template v-if="temp.type">
          <el-form-item v-if="temp.type === 'title'" label="Title" prop="text">
            <el-input v-model="temp.text" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'description'" label="Description" prop="text">
            <el-input v-model="temp.text" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
          </el-form-item>
          <template v-if="temp.type === 'one_big_picture'">
            <el-form-item label="Pict" prop="pict">
              <image-upload />
            </el-form-item>
            <el-form-item label="Click" prop="click">
              <el-input v-model="temp.click">
                <template slot="prepend">
                  <div class="pic-prepend">
                    <el-select
                      v-model="temp.clickPrepend"
                      class="filter-item"
                      placeholder="Please select"
                    >
                      <el-option v-for="item in clickTypes" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-input>
            </el-form-item>
          </template>
          <template v-if="['list_of_clicks', 'list_of_products'].includes(temp.type)">
            <el-form-item label="Mode" prop="mode">
              <el-radio-group v-model="temp.mode">
                <el-radio-button label="wrap" />
                <el-radio-button label="unwrap" />
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="!(temp.type === 'list_of_products')" label="Style" prop="style">
              <el-radio-group v-model="temp.style">
                <el-radio-button label="link" />
                <el-radio-button label="button" />
                <el-radio-button label="picture" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="Item Text">
              <el-input v-model="temp.item.text" />
            </el-form-item>
            <!-- <el-form-item
              v-if="temp.style === 'picture' || temp.type === 'list_of_products'"
              label="Item Pict"
            >
              <image-upload />
            </el-form-item>-->
            <el-form-item label="Item Click">
              <el-input v-model="temp.item.click">
                <template slot="prepend">
                  <div class="pic-prepend">
                    <el-select
                      v-model="temp.item.clickPrepend"
                      class="filter-item"
                      placeholder="Please select"
                    >
                      <el-option v-for="item in clickTypes" :key="item" :label="item" :value="item"></el-option>
                    </el-select>
                  </div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="temp.type === 'list_of_products'" label="Item Price" prop="price">
              <el-input v-model="temp.price"></el-input>
            </el-form-item>
          </template>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="dialogFormVisible = false">Cancel</el-button>
        <el-button v-waves type="primary" @click="createData()">Confirm</el-button>
      </div>
    </el-dialog>

    <!-- views -->
    <el-dialog :visible.sync="dialogViewsVisible" width="65%" destroy-on-close>
      <json-editor v-if="dialogViewsVisible" ref="jsonEditorRef" :value="viewsList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchSectionList,
  updateSectionList
} from '@/api/section'
import JsonEditor from '@/components/JsonEditor'
import waves from '@/directive/waves' // waves directive
import SectionItem from './components/SectionItem.vue'
import ImageUpload from './components/ImageUpload.vue'
import Sortable from 'sortablejs'

export default {
  name: 'SectionList',
  components: { JsonEditor, SectionItem, ImageUpload },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      // viewsList: [],
      listLoading: true,
      calendarTypeOptions: [],
      temp: {
        type: '',
        text: '',
        mode: 'wrap',
        style: 'link',
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        click: '',
        clickPrepend: '',
        item: {
          text: '',
          price: '',
          click: '',
          clickPrepend: '',
          pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'
        }
      },
      clickTypes: ['http://', 'https://', 'activity://', 'open://'],
      expandRowKeys: [],
      dialogFormVisible: false,
      dialogViewsVisible: false,
      sortable: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /* 获取数据 */
    async getList() {
      this.listLoading = true
      const res = await fetchSectionList()
      this.calendarTypeOptions = res.data.typelist;
      this.list = res.data.list.map((item, index) => {
        return {
          items: item.map(m => ({
            ...m, sid: `${Math.random().toString().slice(2)}_${Date.now()}`
          })),
          // items: item,
          id: `${Math.random().toString().slice(2)}_${Date.now()}`,
          types: [].concat(item.map(m => m.type))
        }
      });
      this.listLoading = false
      this.$nextTick(() => {
        this.setSort()
      })
    },
    /* 重置 temp */
    resetTemp() {
      this.temp = {
        type: '',
        text: '',
        mode: 'wrap',
        style: 'link',
        pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3',
        click: '',
        clickPrepend: '',
        item: {
          text: '',
          price: '',
          click: '',
          clickPrepend: '',
          pict: 'https://wpimg.wallstcn.com/e4558086-631c-425c-9430-56ffb46e70b3'
        }
      }
    },
    onChangeType(val) {
      this.resetTemp();
      // console.log(val)
      this.temp.type = val
    },
    /* 打开 弹窗 (创建) */
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 创建 */
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const item = this.formatData(this.temp);
          this.list.push({
            id: `${Math.random().toString().slice(2)}_${Date.now()}`,
            items: [item],
            types: [item.type]
          });
          this.nextTickUpdate();
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    /* 删除 */
    handleDelete(row, index) {
      // const _index = this.list.findIndex(item => item.id === row.id);
      this.list.splice(index, 1);
      if (this.list[index]) {
        this.list[index].types = [].concat(this.list[index].items.map(m => m.type))
      }
      this.nextTickUpdate();
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
    },
    formatData(data) {
      let item = {};
      switch (data.type) {
        case 'title':
        case 'description':
          item = {
            type: data.type,
            text: data.text,
          }
          break;
        case 'one_big_picture':
          item = {
            type: data.type,
            pict: data.pict,
            click: data.clickPrepend + data.click,
          }
          break;
        case 'list_of_clicks':
          item = {
            type: data.type,
            style: data.style,
            mode: data.mode,
            items: [
              {
                text: data.item?.text,
                pict: data.style === 'picture' ? data.item?.pict : '',
                click: data.item?.clickPrepend + data.item?.click,
              }
            ]
          }
          break;
        case 'list_of_products':
          item = {
            type: data.type,
            mode: data.mode,
            items: [
              {
                price: data.item?.price,
                text: data.item?.text,
                pict: data.item?.pict,
                click: data.item?.clickPrepend + data.item?.click,
              }
            ]
          }
          break;
      }
      return item;
    },
    /* 展开/关闭 行 */
    onExpandChange(row, expandedRows) {
      this.expandRowKeys = expandedRows.map(item => `${item.id}`)
    },
    /* 行 拖拽排序 */
    setSort() {
      const el = this.$refs.dragTable.$el.querySelector('.el-table__body-wrapper > table > tbody')
      this.sortable = Sortable.create(el, {
        animation: 180,
        delay: 0,
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        draggable: '.el-table__row',
        setData: (dataTransfer) => {
          this.expandRowKeys = []
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          // console.log(evt.oldIndex, evt.newIndex)
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          this.nextTickUpdate();
        }
      })
    },
    nextTickUpdate() {
      this.$nextTick(() => {
        updateSectionList({ data: this.viewsList }).then(_ => {
          this.dialogFormVisible = false
        })
      })
    },
    onUpdateList({ id, newData }) {
      const section = this.list.find(item => item.id === id);
      section.items = JSON.parse(JSON.stringify(newData));
      section.types = [].concat(newData.map(m => m.type))
      this.nextTickUpdate();
    }
  },
  computed: {
    viewsList() {
      const _list = JSON.parse(JSON.stringify(this.list))
      return _list.map(item => {
        return item.items.map(m => {
          m.sid && delete m.sid;
          return m
        })
      })
    }
  }
}
</script>

<style scoped>
.section-add {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
}
.pic-prepend {
  width: 100px;
}
</style>
